/*
 * @Author: 'zhangkeqq' '2211709169@qq.com'
 * @Date: 2025-07-25 13:17:30
 * @LastEditors: 'zhangkeqq' '2211709169@qq.com'
 * @LastEditTime: 2025-07-28 21:28:38
 * @FilePath: \vue3-admin-node\node-express\router_handle\userinfo.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const db = require('../db/index')
//导入bcrypt加密中间件
const bcrypt  = require('bcryptjs')
//导入node.js的crypto库生成uuid
const crypto = require('crypto')
// 导入fs处理模块
const fs = require('fs')

//注意：这里没有做路径的防重复处理
//上传头像
exports.uploadAvatar = (req,res) =>{
    //生成唯一标识
    const onlyId = crypto.randomUUID()
    let oldName = req.files[0].filename;
    let newName = Buffer.from(req.files[0].originalname,'latin1').toString('utf8')
    fs.renameSync('./public/upload/'+ oldName,'./public/upload/'+ newName)
    const sql = 'insert into image set ?'
    db.query(sql,{
        image_url:`http://127.0.0.1:9000/upload/${newName}`,
        onlyId
    },(err,result)=>{
        if(err) return res.cc(err)
            res.send({
                onlyId,
                status:0,
                url:'http://127.0.0.1:9000/upload/'+ newName
            })
    })
}

//绑定账号
exports.bindAccount = (req,res)=>{
    const {
        account,
        onlyId,
        url
    } = req.body
    const sql = 'update image set account = ? where onlyId =?'
    db.query(sql,[account,onlyId],(err,result)=>{
        if(err) return res.cc(err)
        if(result.affectedRows == 1){
            const sql1 = 'update users set image_url = ? where account = ?'
            db.query(sql1,[url,account],(err,result)=>{
                if(err) return res.cc(err)
                    res.send({
                        status:0,
                        message:'修改成功'
                    })
            })
        }
    })
}

//修改用户密码 先输入旧密码 oldPassword 新密码 newPassword id
exports.changePassword = (req,res)=>{
    const sql = 'select password from users where id = ?'
    db.query(sql,req.body.id,(err,result)=>{
        if(err) return res.cc(err)
        const comparseResult = bcrypt.compareSync(req.body.oldPassword,result[0].password)
        if(!comparseResult){
            return res.send({
                status:1,
                message:'原密码错误'
            })
        }
        req.body.newPassword = bcrypt.hashSync(req.body.newPassword,10)
        const sql1 = 'update users set password = ? where id = ?'
        db.query(sql1,[req.body.newPassword,req.body.id],(err,result)=>{
            if(err) return res.cc(err)
            res.send({
                status:0,
                message:'修改成功'
            })
        })
    })
}

//获取用户信息 接收参数id
exports.getUserInfo = (req,res)=>{
    const sql = 'select * from users where id = ?'
    db.query(sql,req.body.id,(err,result)=>{
        if(err) return res.cc(err)
        result[0].password = ''
        res.send({
            status:0,
            data:result[0]
        })
    })
}
//修改姓名 接收参数id name
exports.changeName = (req,res)=>{
    const {id,name} = req.body
    const sql = 'update users set name = ? where id = ?'
    db.query(sql,[name,id],(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'修改成功'
        })
    })
}

//修改性别 接收参数 id sex
exports.changeSex = (req,res)=>{
    const {id,sex} = req.body
    const sql = 'update users set sex = ? where id =?'
    db.query(sql,[sex,id],(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'修改成功'
        })
    })
}

//修改邮箱
// 修改邮箱 接收参数 id email
exports.changeEmail = (req, res) => {
	const {
		id,
		email
	} = req.body
	const sql = 'update users set email = ? where id = ?'
	db.query(sql, [email, id], (err, result) => {
		if (err) return res.cc(err)
		res.send({
			status: 0,
			message: '修改成功'
		})
	})
}

//验证账户和邮箱是否一致 email account
exports.verifyAccountAndEmail = (req,res)=>{
    const {account,email} = req.body
    const sql = 'select * from users where account = ?'
    db.query(sql,account,(err,result)=>{
        if(err) return res.cc(err)
        if(email == result[0].email){
            res.send({
                status:0,
                message:'查询成功',
                id:result[0].id
            })
        }else{
            res.send({
                status:1,
                message:'查询失败'
            })
        }
    })
}

//登录页面修改密码 参数 newPassword id
exports.changePasswordInLogin = (req,res)=>{
    const user = req.body
    user.newPassword = bcrypt.hashSync(user.newPassword,10)
    const sql = 'update users set password = ? where id = ?'
    db.query(sql,[user.newPassword,user.id],(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'更新成功'
        })
    })
}

//------------------用户管理
//添加管理员
exports.createAdmin = (req,res)=>{
    const {account,password,name,sex,department,email,identity} = req.body
    //判断账号是否存在数据库中
    const sql = 'select * from users where account = ?'
    db.query(sql,account,(err,resluts)=>{
        //判断账号是否存在
        if(resluts.length > 0){
            return res.send({
                status:1,
                message:'账号已存在'
            })
        } 
        const hashpassword = bcrypt.hashSync(password,10)
        //把账号跟密码插入到users表里面
        const sql1 = 'insert into users set ?'
        //创建时间
        const create_time = new Date()
        db.query(sql1,{
            account,
            password:hashpassword,
            name,
            sex,
            department,
            email,
            identity,//身份
            create_time,
            status:0,//初始未冻结状态为0
        },(err,resluts)=>{
            //第一个，插入失败
            //affectedRows为影响的行数，如果插入失败，那么就没有影响的行数，也就是行数不为1
            if(resluts.affectedRows !== 1){
                return res.send({
                    status:1,
                    message:'添加管理员失败'
                })
            }
            res.send({
                status:0,
                message:'添加管理员成功'
            })
        })
    })
}

//获取管理员列表 参数 identity
exports.getAdminList = (req,res)=>{
    const page = parseInt(req.body.page) || 1;
    const pageSize = parseInt(req.body.pageSize) || 10;
    const offset = (page - 1) * pageSize;
    const identity = req.body.identity
    const account = req.body.account
    // const sql = `SELECT *, (SELECT COUNT(*) FROM users WHERE identity = ? and account = ?) AS total_count FROM users WHERE identity = ? and account = ? LIMIT ?, ?`
    const sql = `SELECT *, (SELECT COUNT(*) FROM users WHERE identity = ? and account =  COALESCE(?, account)) AS total_count FROM users WHERE identity = ? and account =  COALESCE(?, account) LIMIT ?, ?`
    db.query(sql,[identity,account, identity,account, offset,pageSize],(err, result) => {
        if(err) return res.cc(err);
        res.send({
            status: 0,
            data: {
                list: result,
                total: result[0].total_count || 0,
                page,
                pageSize
            }
        });
    });
        // result.forEach((e)=>{
        //     e.password=''
        //     e.create_time=''
        //     e.image_url=''
        //     e.status=''
        // })
        // res.send({
        //     status:0,
        //     data:result
        // })
    // })
}

//编辑管理员账号信息
exports.editAdmin = (req,res)=>{
    const {id,name,sex,email,department} = req.body
    const date = new Date()
    const sql = 'select department from users where id = ?'
    db.query(sql,id,(err,result)=>{
        if(result[0].department == department){
            //修改的内容
            const updateContent = {
                id,
                name,
                sex,
                email,
                department,
                update_time:date,
            }
            const sql1 = 'update users set ? where id = ?'
            db.query(sql1,[updateContent,updateContent.id],(err,result)=>{
                if(err) return res.cc(err)
                res.send({
                    status:0,
                    message:'修改管理员信息成功'
                })
            })
        }else{
            //修改的内容
            const updateContent = {
                id,
                name,
                sex,
                email,
                department,
                update_time:date,
                read_list:null,
                read_status:0,
            }
            const sql = 'update users set ? where id = ?'
            db.query(sql,[updateContent,updateContent.id],(err,result)=>{
                if(err) return res.cc(err)
                res.send({
                    status:0,
                    message:'修改管理员信息成功'
                })
            })
        }
    })
}

//对管理员取消赋权 参数 id
exports.changeIdentityToUser = (req,res)=>{
    const identity =  '用户'
    const sql = 'update users set identity = ? where id = ?'
    db.query(sql,[identity,req.body.id],(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'降级成功'
        })
    })
}
//对用户进行赋权 参数id identity
exports.changeIdentityToAdmin = (req,res)=>{
    const date = new Date()
    const sql = 'update users set identity = ?,update_time = ? where id = ?'
    db.query(sql,[req.body.identity,date,req.body.id],(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'赋权成功'
        })
    })
}

//通过账号对用户搜索 account identity
exports.searchUser = (req,res)=>{
    const {account,identity} = req.body
    const sql = 'select * from users where account = ? and identity = ?'
    db.query(sql,[account,identity],(err,result)=>{
        if(err) return res.cc(err)
        result.forEach((e)=>{
            e.password = ''
            e.create_time =''
            e.image_url = ''
            e.status = ''
        })
        res.send({
            status:0,
            data:result
        })
    })
}

//通过部门对用户搜索 department 
exports.searchUserByDepartment = (req,res) => {
    const sql = 'select * from users where department = ? and identity = "用户"'
    db.query(sql,req.body.department,(err,result)=>{
        if(err) return res.cc(err)
        result.forEach((e)=>{
            e.password = ''
            e.image_url = ''
        })
        res.send({
            ststus:0,
            data:result
        })
    })
}

//冻结账号/解冻账号 通过id 把status 置为1
exports.banHotUser = (req,res)=>{
    const {status,id} = req.body
    const sql = 'update users set status = ? where id = ?'
    db.query(sql,[status,id],(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'冻结成功'
        })
    })
}

//获取冻结用户列表
exports.getBanList = (req,res)=>{
    const sql = 'select * from users where status = "1"'
    db.query(sql,(err,result)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            data:result
        })
    })
}

//删除用户id account
exports.deleteUser = (req,res)=>{
    const sql = 'delete from users where id = ?'
    db.query(sql,req.body.id,(err,result)=>{
        if(err) return res.cc(err)
        const sql1 = 'delect from image where account = ?'
        db.query(sql1,req.body.account,(err,result)=>{
            if(err) return res.cc(err)
            res.send({
                status:0,
                message:'删除用户成功'
            })
        })
    })
}